package chatgpt.test;

import cn.hutool.poi.excel.ExcelReader;
import com.dataprocessor.util.TextUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) {
//        String txtpath = "D:/companyinfo.txt";
//        TextUtils.appendTxt("123",txtpath);
        readExcel();
    }



    //



    public static void  readExcel(){
        String mainExccel = "D:\\wx_file\\WeChat Files\\xq16109756\\FileStorage\\File\\2024-01\\爬的3950、文章.xlsx";
        File duibiExccelFile = new File(mainExccel);
        ExcelReader duibireader = cn.hutool.poi.excel.ExcelUtil.getReader(duibiExccelFile);
        List<Map<String, Object>> duibimaps = duibireader.readAll();

        String txtpath = "D:/companyinfo.txt";
        String temple = "帮我找一下这几个公司的官网地址、简介。公司名单：{companys}。无需任何解释。按照我得要求告诉我即可。回答参照如下：公司名称要求用<company></company>包裹不得出现公司名无关的描述，   每个自然段参照实例：<company>company name</company>   <p>Introduction: Freedom Concepts is known for designing and manufacturing adaptive bicycles, tricycles, and mobility devices for individuals with disabilities. They provide a range of customizable options to suit different needs. </p><p> Website: <a href=\\\"https://www.freedomconcepts.com/\\\">Freedom Concepts</a></p>；";
        Map<String, Object> row1 = null;
        ArrayList<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
        String answer = "";
        for(Map dmap:duibimaps) {
            System.out.println(dmap);
            String prompts = String.valueOf(dmap.get("Companies "));
            prompts = prompts.replace("\n",",");
            prompts = temple.replace("{companys}",prompts);
            System.out.println(prompts);
            answer = toGo(prompts)+"\n--------\n";
            TextUtils.appendTxt(answer,txtpath);

        }
    }

    public static String toGo(String content) {
        String answer = "";
        try {
            URL url = new URL("http://ai.qujiami.cn/api/openai/v1/chat/completions");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();

            String body = "{\"messages\":[{\"role\":\"user\",\"content\":\""+content+"\"}],\"stream\":true,\"model\":\"gpt-4\",\"temperature\":0.5,\"presence_penalty\":0,\"frequency_penalty\":0,\"top_p\":1}";

            OutputStream os = conn.getOutputStream();
            os.write(body.getBytes("UTF-8"));
            os.flush();
            os.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("data: ")) {
                    try {
                        String jsonStr = line.substring(6); // 去掉前面的 "data: "
                        JsonObject jsonObj = JsonParser.parseString(jsonStr).getAsJsonObject();
                        if (jsonObj.has("choices")) {
                            JsonObject choice = jsonObj.getAsJsonArray("choices").get(0).getAsJsonObject();
                            if (choice.has("delta") && choice.getAsJsonObject("delta").has("content")) {
                                response.append(choice.getAsJsonObject("delta").get("content").getAsString());
                            }
                        }
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }

                }
            }
            reader.close();
            conn.disconnect();
            System.out.println("---------" + response.toString());
            answer = response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return answer;
    }

    public static void main2(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("http://ai.qujiami.cn/api/openai/v1/chat/completions");

            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json");

            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);

            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);

            // Post 请求不能使用缓存
            conn.setUseCaches(false);

            // 连接,上述至此的配置必须要在connect之前完成
            conn.connect();

            // 创建数据
            String body = "{\"messages\":[{\"role\":\"user\",\"content\":\"昨天的当天的明天是哪天？\"}],\"stream\":true,\"model\":\"gpt-4\",\"temperature\":0.5,\"presence_penalty\":0,\"frequency_penalty\":0,\"top_p\":1}";

            // 写入数据
            OutputStream os = conn.getOutputStream();
            os.write(body.getBytes("UTF-8"));
            os.flush();
            os.close();

            // 获取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            conn.disconnect();
            System.out.println("Response: " + response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
